/*******************************************************************************
 * Copyright 2020 huanggefan.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/

package action

import (
	"gorm.io/gorm"

	"gitee.com/WisdomClassroom/cli/glb"
	"gitee.com/WisdomClassroom/core/models"
)

func initDB(db *gorm.DB) bool {
	tx := db.Begin()

	if !initForUser(tx) {
		tx.Rollback()
		return false
	}
	if !initForCourse(tx) {
		tx.Rollback()
		return false
	}
	if !initForClass(tx) {
		tx.Rollback()
		return false
	}
	if !initForChapter(tx) {
		tx.Rollback()
		return false
	}
	if !initForQuestion(tx) {
		tx.Rollback()
		return false
	}
	if !initForResource(tx) {
		tx.Rollback()
		return false
	}

	tx.Commit()
	return true
}

func initForUser(db *gorm.DB) bool {
	var err error
	err = db.AutoMigrate(&models.User{})
	if err != nil {
		glb.Logger.Error("Migrate database 'User' error: " + err.Error())
		return false
	}
	glb.Logger.Info("Start migrate database 'User' finish.")

	return true
}
func initForClass(db *gorm.DB) bool {
	var err error

	err = db.AutoMigrate(&models.ClassModel{})
	if err != nil {
		glb.Logger.Error("Migrate database 'ClassModel' error: " + err.Error())
		return false
	}
	glb.Logger.Info("Start migrate database 'ClassModel' finish.")

	return true
}
func initForCourse(db *gorm.DB) bool {
	var err error

	err = db.AutoMigrate(&models.Course{})
	if err != nil {
		glb.Logger.Error("Migrate database 'Course' error: " + err.Error())
		return false
	}
	glb.Logger.Info("Start migrate database 'Course' finish.")

	return true
}
func initForChapter(db *gorm.DB) bool {
	var err error

	err = db.AutoMigrate(&models.Chapter{})
	if err != nil {
		glb.Logger.Error("Migrate database 'Chapter' error: " + err.Error())
		return false
	}
	glb.Logger.Info("Start migrate database 'Chapter' finish.")

	return true
}
func initForQuestion(db *gorm.DB) bool {
	var err error

	err = db.AutoMigrate(&models.Question{})
	if err != nil {
		glb.Logger.Error("Migrate database 'Question' error: " + err.Error())
		return false
	}
	glb.Logger.Info("Start migrate database 'Question' finish.")

	return true
}
func initForResource(db *gorm.DB) bool {
	var err error

	err = db.AutoMigrate(&models.Resource{})
	if err != nil {
		glb.Logger.Error("Migrate database 'Resource' error: " + err.Error())
		return false
	}
	glb.Logger.Info("Start migrate database 'Resource' finish.")

	return true
}
